'use strict';

const axios = require('axios')
const urljoin = require('url-join');
const semver = require('semver')

// 1.根据npm包名请求npm信息
function npmGetInfo(npmName, registry) {
  // TODO
  if (!npmName) {
    return null;
  }
  return axios.get(urljoin(getDefaultRegistry(), npmName)).then((res) => {
    if (res.status === 200) {
      return res.data
    }
  }).catch((err) => {
    Promise.reject(err)
  })
}

// 获取registry
function getDefaultRegistry(isOriginal = false) {
  // 两个源返回的versions的排序相反
  return isOriginal ? 'https://registry.npmjs.org/' : 'https://registry.npm.taobao.org/'
}

// 2.获取npm包的版本合集
async function getNpmVersions(npmName, registry) {
  const data = await npmGetInfo(npmName, registry)
  if (data) {
    return Object.keys(data.versions)
  } else {
    return []
  }
}

// 3.获取比对大于当前版本号的版本合集
function getSemverVersions(baseVersion, versions) {
  return versions.filter(version => {
    return semver.satisfies(version, `^${baseVersion}`)
  }).sort((a, b) => {
    return semver.gt(b, a)
  })
}

async function getNpmSemverVersions(baseVersion, npmName, registry) {
  const versions = await getNpmVersions(npmName, registry)
  const newVersions = getSemverVersions(baseVersion, versions)
  if (newVersions && newVersions.length > 0) {
    return newVersions[0]
  }
}

async function getLastestVersion(npmName, registry) {
  const versions = await getNpmVersions(npmName, registry)
  return versions[0]
}

module.exports = {
  getNpmVersions,
  getNpmSemverVersions,
  getDefaultRegistry,
  getLastestVersion
};
